package cn.market.service.product.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.persistence.Query;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.market.bean.QueryResult;
import cn.market.bean.product.Brand;
import cn.market.bean.product.ProductInfo;
import cn.market.bean.product.ProductStyle;
import cn.market.bean.product.ProductType;
import cn.market.bean.user.Market;
import cn.market.service.base.DaoSupport;
import cn.market.service.product.ProductInfoService;
import cn.market.service.product.ProductTypeService;
import cn.market.utils.Log;


@Service
@Transactional
public class ProductInfoServiceBean extends DaoSupport<ProductInfo> implements ProductInfoService {
	@Resource(name="productTypeServiceBean") private ProductTypeService productTypeService;
	private String TAG = "ProductInfoServiceBean";
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<ProductInfo> getViewHistory(Integer[] productids, int maxResult){
		StringBuffer jpql = new StringBuffer();
		for(int i=0 ;i<productids.length; i++){
			jpql.append('?').append(i).append(',');
		}
		jpql.deleteCharAt(jpql.length()-1);
		Query query = em.createQuery("select o from ProductInfo o where o.id in("+ jpql.toString()+")");
		for(int i=0 ;i<productids.length; i++){
			query.setParameter(i, productids[i]);
		}
		query.setFirstResult(0).setMaxResults(maxResult);
		return query.getResultList();
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<ProductInfo> getTopSell(Integer typeid, int maxResult){
		List<Integer> typeids = new ArrayList<Integer>();
		typeids.add(typeid);
		getTypeids(typeids, new Integer[]{typeid});
		StringBuffer n = new StringBuffer();
		for(int i=0; i<typeids.size();i++){
			n.append('?').append((i+2)).append(',');
		}
		n.deleteCharAt(n.length()-1);
		Query query = em.createQuery("select o from ProductInfo o where o.commend=?1 and o.type.typeid in("+ n.toString()+") order by o.sellcount desc");
		query.setParameter(1, true);		
		for(int i=0; i<typeids.size();i++){
			query.setParameter(i+2, typeids.get(i));
		}
		query.setFirstResult(0).setMaxResults(maxResult);
		return query.getResultList();
	}
	
	private void getTypeids(List<Integer> outtypeids, Integer[] typeids){
		List<Integer> subtypeids = productTypeService.getSubTypeid(typeids);
		if(subtypeids!=null && subtypeids.size()>0){
			outtypeids.addAll(subtypeids);
			Integer[] ids = new Integer[subtypeids.size()];
			for(int i=0;i<subtypeids.size();i++){
				ids[i]=subtypeids.get(i);
			}
			getTypeids(outtypeids, ids);
		}
	}

	@SuppressWarnings("unchecked")
	@Transactional(readOnly=true,propagation=Propagation.NOT_SUPPORTED)
	public List<Brand> getBrandsByProductTypeid(Integer[] typeids){
		if(typeids!=null && typeids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0;i<typeids.length;i++){
				jpql.append('?').append((i+1)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);			
			Query query = em.createQuery("select o from Brand o where o.code in(select p.brand.code from ProductInfo p where p.type.typeid in("+ jpql.toString()+") group by p.brand.code)");
			for(int i=0;i<typeids.length;i++){
				query.setParameter(i+1, typeids[i]);
			}
			return query.getResultList();
		}
		return null;
	}
	
	public void setCommendStatu(Integer[] productids, boolean statu) {
		if(productids!=null && productids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0;i<productids.length;i++){
				jpql.append('?').append((i+2)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update ProductInfo o set o.commend=?1 where o.id in("+ jpql.toString()+ ")");
			query.setParameter(1, statu);
			for(int i=0;i<productids.length;i++){
				query.setParameter(i+2, productids[i]);
			}
			query.executeUpdate();
		}
	}

	public void setVisibleStatu(Integer[] productids, boolean statu) {
		if(productids!=null && productids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i=0;i<productids.length;i++){
				jpql.append('?').append((i+2)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update ProductInfo o set o.visible=?1 where o.id in("+ jpql.toString()+ ")");
			query.setParameter(1, statu);
			for(int i=0;i<productids.length;i++){
				query.setParameter(i+2, productids[i]);
			}
			query.executeUpdate();
		}
	}

	@Override
	public ProductInfo find(Serializable entityId) {
		ProductInfo info = null;
		String sql ="from ProductInfo o where o.id=?1";
		Query query = em.createQuery(sql);
		query.setParameter(1, entityId);
		info = (ProductInfo)query.getSingleResult();
		return info;
	}

	@Override
	public void setsalesPromotion(Integer[] productids, boolean statu) {
		if(productids!=null && productids.length>0){
			StringBuffer jpql = new StringBuffer();
			for(int i =0; i<productids.length;i++){
				jpql.append('?').append((i+2)).append(',');
			}
			jpql.deleteCharAt(jpql.length()-1);
			Query query = em.createQuery("update ProductInfo o set o.salesPromotion=?1 where o.id in("+ jpql.toString()+ ")");
			query.setParameter(1, statu);
			for(int i=0;i<productids.length;i++){
				query.setParameter(i+2, productids[i]);
			}
			query.executeUpdate();
		}
	}

	@Override
	public QueryResult<ProductInfo> getIndexProductinfos(String hql,
			String wherejpql, int firstindex, int maxresult,
			Object[] queryParams, LinkedHashMap<String, String> orderby) {
		List list = super.getScrollData(hql, wherejpql, firstindex, maxresult, queryParams, orderby);
		QueryResult<ProductInfo> qr = new QueryResult<ProductInfo>();
		qr.setResultlist(encapsulation2products(list));
		qr.setTotalrecord(super.getCount());
		return qr;
	}
	
	public List<ProductInfo> encapsulation2products(List list){
		String methodName = "encapsulation2products() ";
		List<ProductInfo> productInfoes = new ArrayList<ProductInfo>();
		if(list != null && list.size()>0){
			for(int i=0;i<list.size();i++){
				ProductInfo productInfo = new ProductInfo();
				Object [] obj = (Object [])list.get(i);
				productInfo.setId(new Integer(String.valueOf(obj[0])));
				productInfo.setName(String.valueOf(obj[1]));
				productInfo.setCode(String.valueOf(obj[2]));
				productInfo.setMarketprice(new Float(String.valueOf(obj[3])));
				productInfo.setSellprice(new Float(String.valueOf(obj[4])));
				productInfo.setBaseprice(new Float(String.valueOf(obj[5])));
				ProductStyle style = new ProductStyle();
				style.setId(new Integer(String.valueOf(obj[6])));
				style.setImagename(String.valueOf(obj[7]));
				style.setName(String.valueOf(obj[8]));
				Set<ProductStyle> styles = new HashSet<ProductStyle>();
				styles.add(style);
				ProductType type = new ProductType();
				type.setTypeid(new Integer(String.valueOf(obj[9])));
				//Log.println(TAG, methodName+"-- the typeid is:"+String.valueOf(obj[7]));
				productInfo.setType(type);
				style.setProduct(productInfo);
				Market market = new Market();
				market.setId(new Integer(String.valueOf(obj[10])));
				market.setName(String.valueOf(obj[11]));
				productInfo.setParent(market);
				productInfo.setStyles(styles);
				productInfoes.add(productInfo);
				//Log.println(TAG, methodName+"-- the style image path is:"+productInfo.getStyles().iterator().next().getImage140FullPath());
			}
		}
		return productInfoes;
	}

	@Override
	public QueryResult<ProductInfo> getAllProductInfo(String sql, String where,
			int first, int max, Object[] params,
			LinkedHashMap<String, String> orderby) {
		QueryResult<ProductInfo> qr = new QueryResult<ProductInfo>();
		List list = getScrollData(sql, where, first, max, params, orderby);
		qr.setResultlist(encapsulation2products_background(list));
		return qr;
	}
	
	public List<ProductInfo> encapsulation2products_background(List list){
		List<ProductInfo> infos= new ArrayList<ProductInfo>();
		String methodName = "encapsulation2products_background() ";
		Log.println(TAG, methodName+" -- the list is:"+list);
		if(list != null && list.size()>0){
			Log.println(TAG, methodName+" -- the list size is:"+list.size());
			for (int i=0;i<list.size();i++){
				Object [] obj =(Object[]) list.get(i);
				ProductInfo info = new ProductInfo();
				info.setId(new Integer(String.valueOf(obj[0])));
				info.setCode(String.valueOf(obj[1]));
				info.setName(String.valueOf(obj[2]));
				info.setBaseprice(new Float(String.valueOf(obj[3])));
				info.setSellprice(new Float(String.valueOf(obj[4])));
				info.setVisible(Boolean.valueOf(String.valueOf(obj[5])));
				info.setCommend(Boolean.valueOf(String.valueOf(obj[6])));
				info.setSalesPromotion(Boolean.valueOf(String.valueOf(obj[7])));
				
				ProductType type = new ProductType();
				type.setName(String.valueOf(obj[8]));
				info.setType(type);
				infos.add(info);
			}
		}
		return infos;
	}
}
